//
//  BeautyViewController.m
//  YMJReadColor
//
//  Created by 殷殷明静 on 16/9/10.
//  Copyright © 2016年 MJ.Y. All rights reserved.
//

#import "RecommendViewController.h"
#import "DomesticViewController.h"
#import "DetailViewController.h"
#import "HomeViewController.h"
#import "MainViewController.h"
#import "HomeTableViewCell.h"
#import "HomeTableViewSecondCell.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "YMJMacro_h.h"
#import "DataModel.h"
#import "Model.h"
#import "JHRefresh.h"
#import "MJRefresh.h"
#import "UIScrollView+JHRefresh.h"
@interface RecommendViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) HomeViewController *homeVC;

@end

@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createView];
    [self createData];
    [self refresh];
}
- (void)createView {
    // 获得viewController
    UIWindow *windows = [[UIApplication sharedApplication] keyWindow];
    MainViewController *tab= (MainViewController *)windows.rootViewController;
    UINavigationController *homenavc = (UINavigationController *)[tab.viewControllers firstObject];
    _homeVC = (HomeViewController *)[homenavc.viewControllers firstObject];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 108) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
//    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"1"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeTableViewSecondCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"2"];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    DataModel *data = _dataArray[indexPath.row];
    if (data.imageDTOList.count == 2) {
        return 180;
    } else {
        return 76;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DataModel *data = _dataArray[indexPath.row];
    if (data.imageDTOList.count == 2) {
        HomeTableViewSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:@"2"];
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:[data.imageDTOList lastObject].src]];
        cell.myTitleLabel.text = data.title;
        cell.myOriginLabel.text = data.origin;
        
        return cell;
    } else {
        HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"1"];
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:[data.imageDTOList lastObject].src]];
        cell.myTitleLabel.text = data.title;
        cell.myOriginLabel.text = data.origin;
        return cell;
    }
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DetailViewController *detailVC = [DetailViewController new];
    DataModel *data = self.dataArray[indexPath.row];
    detailVC.messageId = data.messageId;
    detailVC.categoryIds = data.categoryIds;
    detailVC.infomation = data.title;
    detailVC.parentId = data.parentId;
    detailVC.parentType = data.parentType;
    detailVC.messageType = data.messageType;
    /*收藏*/
    detailVC.newsId = data.messageId;
    detailVC.newsType = data.messageType;
    detailVC.newsEngineType = data.engineType;
    detailVC.layoutType = data.layoutType;
    [self.homeVC setHidesBottomBarWhenPushed:YES];
    [self.homeVC.navigationController pushViewController:detailVC animated:YES];
    [self.homeVC setHidesBottomBarWhenPushed:NO];
    
}
- (void)createData{
    
    /*缓存沙盒路径 */
    NSString *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    /*首页文件夹*/
    NSFileManager*fileManager = [NSFileManager defaultManager];
    NSString *homePath = [cache stringByAppendingPathComponent:@"homeNews"];
    BOOL res = [fileManager createDirectoryAtPath:homePath withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        /*推荐子文件夹*/
        NSString *recommendPath = [homePath stringByAppendingPathComponent:@"recommend"];
        BOOL res1 = [fileManager createDirectoryAtPath:recommendPath withIntermediateDirectories:YES attributes:nil error:nil];
        if (res1) {
            
            
            /*存入数据*/
            
            NSString *path = [recommendPath stringByAppendingPathComponent:@"recommend.plist"];
            
            /*先读出沙盒文件*/
            BOOL res1 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            if (res1) {
                
                
                /*读取文件*/
                _dataArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
                
                /*如果数量多于30个,只要前30个*/
                if (_dataArray.count > 30) {
                    for (int i = 31; i < _dataArray.count; i++) {
                        [_dataArray removeObjectAtIndex:i];
                    }
                }
            }
            
            
        }
        
    }
    
    

    
}
- (void)refresh {
    
    /*下拉刷新 */
    
    __weak RecommendViewController *weakSelf = self;
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshAmazingAniView class] beginRefresh:^{
        // 延时1秒再刷新
        
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                YMJNetWorking *gns = [YMJNetWorking shareNetWorking];
                if (![gns updateInterfaceWithReachability]) {
                    [weakSelf.tableView headerEndRefreshingWithResult:JHRefreshResultFailure];
                } else {
                    int rand = 6;
                    // 生成时间戳
                    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
                    NSTimeInterval a = [dat timeIntervalSince1970] * 1000;
                    NSString *timeString = [NSString stringWithFormat:@"%.0f",a];
                    NSString *randURL = [NSString stringWithFormat:@"http://api.9wuli.com/v1/message/summary?channelId=252093f833140ad315ddd40407ef0e1b&pageSize=%d&since=%@&slipType=DOWN&appId=15cba93584fa09ed2873fefcdc9b08c9&appSecret=49759a039852e3f826d8754f0b13cb47",rand,timeString];
                    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                    [manager.requestSerializer setValue:@"Dalvik/1.6.0 (Linux; U; Android 4.2.1; R823T Build/JOP40D) Sdk/0.2.0 (agent:s;channel:venus;deviceId:863331028674542;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:4.2.1;idfa:null)" forHTTPHeaderField:@"User-Agent"];
                    [manager.requestSerializer setValue:@"api.9wuli.com" forHTTPHeaderField:@"Host"];
                    [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
                    [manager GET:randURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        NSDictionary *dic = responseObject;
                        
                        Model *mo = [Model modelWithDic:dic];
                        NSMutableArray *downArray = [NSMutableArray arrayWithArray:mo.data];
                        
                        if (downArray.count == 0) {
                            [weakSelf.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess dataCount:downArray.count];
                        } else {
                            [weakSelf.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess dataCount:downArray.count];
                            NSArray *currentArray = weakSelf.dataArray;
                            [downArray addObjectsFromArray:currentArray];
                            weakSelf.dataArray = downArray;
                            [weakSelf.tableView reloadData];
                            /*存入数据*/
                            NSString *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
                            NSString *homePath = [cache stringByAppendingPathComponent:@"homeNews"];
                            NSString *recommendPath = [homePath stringByAppendingPathComponent:@"recommend"];
                            NSString *path = [recommendPath stringByAppendingPathComponent:@"recommend.plist"];
                            [NSKeyedArchiver archiveRootObject:weakSelf.dataArray toFile:path];
                        }
                       
                        
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        
                        
                    }];
                }
                
                
            });
        
        
     
    }];
    

   
    // 上拉刷新
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshAmazingAniView class] beginRefresh:^{
        // 生成随机数
       int rand = (4 + arc4random() % (6 - 4 + 1));
        // 生成时间戳
        NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a = [dat timeIntervalSince1970] * 1000;
        NSString *timeString = [NSString stringWithFormat:@"%.0f",a];
        NSString *randURL = [NSString stringWithFormat:@"http://api.9wuli.com/v1/message/summary?channelId=252093f833140ad315ddd40407ef0e1b&pageSize=%d&since=%@&slipType=UP&appId=15cba93584fa09ed2873fefcdc9b08c9&appSecret=49759a039852e3f826d8754f0b13cb47",rand,timeString];
        // 延时2秒再刷新
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            [manager.requestSerializer setValue:@"Dalvik/1.6.0 (Linux; U; Android 4.2.1; R823T Build/JOP40D) Sdk/0.2.0 (agent:s;channel:venus;deviceId:863331028674542;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:4.2.1;idfa:null)" forHTTPHeaderField:@"User-Agent"];
            [manager.requestSerializer setValue:@"api.9wuli.com" forHTTPHeaderField:@"Host"];
            [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
            [manager GET:randURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dic = responseObject;
                Model *mo = [Model modelWithDic:dic];
                NSArray *dataAr = [NSArray arrayWithArray:mo.data];
                if (dataAr.count == 0) {
                    [weakSelf.tableView footerEndRefreshing];
                } else {
                    [weakSelf.dataArray addObjectsFromArray:dataAr];
                    [weakSelf.tableView reloadData];
                    
                    [weakSelf.tableView footerEndRefreshing];
                    /*存入数据*/
                    NSString *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
                    NSString *homePath = [cache stringByAppendingPathComponent:@"homeNews"];
                    NSString *recommendPath = [homePath stringByAppendingPathComponent:@"recommend"];
                    NSString *path = [recommendPath stringByAppendingPathComponent:@"recommend.plist"];
                    [NSKeyedArchiver archiveRootObject:weakSelf.dataArray toFile:path];
                }
               
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                
            }];
           
            // 第二个页面网络请求
            
        });
        
    }];
    
    
    
    [_tableView headerStartRefresh];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if ([scrollView isEqual:_tableView]) {
        if (scrollView.contentOffset.y == scrollView.contentSize.height - scrollView.frame.size.height) {
            int rand = (4 + arc4random() % (6 - 4 + 1));
            // 生成时间戳
            NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
            NSTimeInterval a = [dat timeIntervalSince1970] * 1000;
            NSString *timeString = [NSString stringWithFormat:@"%.0f",a];
            NSString *randURL = [NSString stringWithFormat:@"http://api.9wuli.com/v1/message/summary?channelId=252093f833140ad315ddd40407ef0e1b&pageSize=%d&since=%@&slipType=UP&appId=15cba93584fa09ed2873fefcdc9b08c9&appSecret=49759a039852e3f826d8754f0b13cb47",rand,timeString];
            // 立即刷新
                
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                [manager.requestSerializer setValue:@"Dalvik/1.6.0 (Linux; U; Android 4.2.1; R823T Build/JOP40D) Sdk/0.2.0 (agent:s;channel:venus;deviceId:863331028674542;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:4.2.1;idfa:null)" forHTTPHeaderField:@"User-Agent"];
                [manager.requestSerializer setValue:@"api.9wuli.com" forHTTPHeaderField:@"Host"];
                [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
                [manager GET:randURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSDictionary *dic = responseObject;
                    Model *mo = [Model modelWithDic:dic];
                    NSArray *dataAr = [NSArray arrayWithArray:mo.data];
                    [self.dataArray addObjectsFromArray:dataAr];
                    [self.tableView reloadData];
                    /*存入数据*/
                    NSString *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
                    NSString *homePath = [cache stringByAppendingPathComponent:@"homeNews"];
                    NSString *recommendPath = [homePath stringByAppendingPathComponent:@"recommend"];
                    NSString *path = [recommendPath stringByAppendingPathComponent:@"recommend.plist"];
                    [NSKeyedArchiver archiveRootObject:_dataArray toFile:path];
                    
                    
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                    
                }];
                
            

        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */



@end
